<template>
	<view class="container">
		<!-- 1. 本地视频选择区域 -->
		<view class="section">
			<text class="section-title">1. 选择本地视频 {{test}}</text>
			<button class="operation-btn" @click="checkAlbumPermission" :disabled="isRecording">
				选择视频文件
			</button>
			<text class="hint">支持从相册选择，视频时长需在3-10秒之间</text>

			<!-- 本地视频时长警告 -->
			<view v-if="showLocalVideoWarning" class="warning-message">
				<text class="warning-icon">⚠️</text>
				<text>本地视频时长不符合要求（需3-10秒），请重新选择！</text>
			</view>

			<!-- 本地视频选择成功提示 -->
			<view v-if="selectedVideoUrl && !showLocalVideoWarning" class="success-message">
				<text class="success-icon">✓</text>
				<text>本地视频选择成功，时长符合要求</text>
			</view>
		</view>

		<!-- 2. 视频录制区域 -->
		<view class="section">
			<text class="section-title">2. 视频录制</text>
			<view class="control-group">
				<button class="operation-btn start-btn" @click="checkCameraPermission" :disabled="isRecording">
					开始录制
				</button>
				<button class="operation-btn stop-btn" @click="stopRecording" :disabled="!isRecording">
					停止录制
				</button>
			</view>

			<!-- 录制状态显示 -->
			<view v-if="isRecording" class="recording-status">
				<view class="recording-dot"></view>
				<text>正在录制... 已录制: {{ recordedSeconds }} 秒</text>
			</view>

			<!-- 录制时长警告 -->
			<view v-if="showRecordWarning" class="warning-message">
				<text class="warning-icon">⚠️</text>
				<text>{{ recordWarningText }}</text>
			</view>

			<!-- 录制成功提示及保存按钮 -->
			<view v-if="recordedVideoUrl && !showRecordWarning" class="success-group">
				<text class="success-icon">✓</text>
				<text>视频录制成功，时长符合要求</text>
				<button class="operation-btn save-btn" @click="checkSavePermission">
					保存视频到相册
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 本地视频相关
				selectedVideoUrl: null,
				selectedVideoDuration: 0,
				showLocalVideoWarning: false,
				test:'11111',

				// 录制相关
				cameraCtx: null,
				isRecording: false,
				recordedVideoUrl: null,
				minRecordDuration: 3, // 最小录制时长(秒)
				maxRecordDuration: 10, // 最大录制时长(秒)
				recordedSeconds: 0,
				recordingTimer: null,
				showRecordWarning: false,
				recordWarningText: ''
			};
		},

		onLoad() {
			// 初始化摄像头上下文
			this.cameraCtx = uni.createCameraContext(this);
		},

		onUnload() {
			// 页面卸载时清理资源
			if (this.recordingTimer) {
				clearInterval(this.recordingTimer);
			}

			// 如果正在录制，停止录制
			if (this.isRecording) {
				this.cameraCtx.stopRecord();
			}
		},

		methods: {
			/**
			 * 检查相册权限
			 * 选择本地视频前需要获取相册访问权限
			 */
			checkAlbumPermission() {
				this.chooseLocalVideo();
			},

			/**
			 * 检查摄像头权限
			 * 录制视频前需要获取摄像头权限
			 */
			checkCameraPermission() {
				this.startRecording();
			},

			/**
			 * 检查保存到相册权限
			 * 保存视频前需要获取相册写入权限
			 */
			checkSavePermission() {
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success: () => {
						// 已授权，保存视频
						this.saveVideo();
					},
					fail: () => {
						// 未授权，提示用户并引导开启
						this.showPermissionModal('需要保存权限', '请在设置中开启保存到相册权限');
					}
				});
			},

			/**
			 * 显示权限申请弹窗
			 * @param {String} title - 弹窗标题
			 * @param {String} content - 弹窗内容
			 */
			showPermissionModal(title, content) {
				uni.showModal({
					title,
					content,
					cancelText: '取消',
					confirmText: '去设置',
					success: (res) => {
						if (res.confirm) {
							// 打开设置页
							uni.openSetting({
								success: (settingResult) => {
									console.log('设置结果:', settingResult);
								}
							});
						}
					}
				});
			},

			/**
			 * 选择本地视频文件
			 * 使用uni.chooseVideo API
			 */
			chooseLocalVideo() {
				uni.chooseVideo({
					// sourceType: ['album'], // 只从相册选择
					sourceType: ['album', 'camera'],
					maxDuration: this.maxRecordDuration, // 最大时长限制
					camera: 'back',
					success: (res) => {
						// 保存视频路径和时长
						this.selectedVideoUrl = res.tempFilePath;
						this.selectedVideoDuration = res.duration;
						this.showLocalVideoWarning = false;

						// 验证视频时长
						if (this.selectedVideoDuration < this.minRecordDuration ||
							this.selectedVideoDuration > this.maxRecordDuration) {
							this.showLocalVideoWarning = true;
							this.selectedVideoUrl = null; // 清除不符合要求的视频
						}
					},
					fail: (err) => {
						console.error('选择视频失败:', err);
						if (err.errMsg !== 'chooseVideo:fail cancel') { // 排除用户取消的情况
							uni.showToast({
								title: '选择视频失败',
								icon: 'none'
							});
						}
						if (err.errMsg.includes("auth deny")) {
							// 用户拒绝授权相册，引导到设置页开启
							uni.showModal({
								title: "需要相册权限",
								content: "请在设置中开启相册权限以选择视频",
								success: (modalRes) => {
									if (modalRes.confirm) {
										uni.openSetting(); // 打开小程序设置页
									}
								}
							});
						}
					}
				});
			},

			/**
			 * 开始录制视频
			 * 小程序中使用cameraContext.startRecord()
			 */
			startRecording() {
				// 重置录制相关状态
				this.showRecordWarning = false;
				this.recordedVideoUrl = null;
				this.recordedSeconds = 0;
				this.isRecording = true;

				// 开始录制，关闭音频录制
				this.cameraCtx.startRecord({
					audio: false, // 不录制音频
					success: () => {
						console.log('录制开始');
						// 启动计时器
						this.recordingTimer = setInterval(() => {
							this.recordedSeconds++;

							// 达到最大时长自动停止
							if (this.recordedSeconds >= this.maxRecordDuration) {
								this.stopRecording();
								uni.showToast({
									title: `已达到最大${this.maxRecordDuration}秒`,
									icon: 'none'
								});
							}
						}, 1000);
					},
					fail: (err) => {
						console.error('录制启动失败:', err);
						this.isRecording = false;
						uni.showToast({
							title: '录制失败，请检查权限',
							icon: 'none'
						});
					}
				});
			},

			/**
			 * 停止录制视频
			 */
			stopRecording() {
				if (!this.isRecording) return;

				// 清除计时器
				clearInterval(this.recordingTimer);

				// 停止录制
				this.cameraCtx.stopRecord({
					success: (res) => {
						this.isRecording = false;
						const tempVideoPath = res.tempVideoPath;

						// 验证录制时长
						if (this.recordedSeconds < this.minRecordDuration) {
							this.showRecordWarning = true;
							this.recordWarningText = `录制时长不足${this.minRecordDuration}秒，请重新录制！`;

							// 删除不符合要求的临时文件
							uni.removeSavedFile({
								filePath: tempVideoPath
							});
							return;
						}

						// 二次验证视频实际时长
						this.verifyVideoDuration(tempVideoPath);
					},
					fail: (err) => {
						console.error('录制停止失败:', err);
						this.isRecording = false;
						uni.showToast({
							title: '录制停止失败',
							icon: 'none'
						});
					}
				});
			},

			/**
			 * 验证视频实际时长
			 */
			verifyVideoDuration(filePath) {
				uni.getVideoInfo({
					src: filePath,
					success: (res) => {
						const actualDuration = res.duration;

						// 再次验证时长
						if (actualDuration < this.minRecordDuration) {
							this.showRecordWarning = true;
							this.recordWarningText =
								`视频实际时长${actualDuration.toFixed(1)}秒，不足${this.minRecordDuration}秒！`;
							uni.removeSavedFile({
								filePath: filePath
							});
						} else if (actualDuration > this.maxRecordDuration) {
							this.showRecordWarning = true;
							this.recordWarningText =
								`视频实际时长${actualDuration.toFixed(1)}秒，超过${this.maxRecordDuration}秒！`;
							uni.removeSavedFile({
								filePath: filePath
							});
						} else {
							// 时长符合要求
							this.showRecordWarning = false;
							this.recordedVideoUrl = filePath;
						}
					},
					fail: (err) => {
						console.error('获取视频信息失败:', err);
						this.showRecordWarning = true;
						this.recordWarningText = '获取视频信息失败，请重新录制！';
					}
				});
			},

			/**
			 * 保存视频到相册
			 */
			saveVideo() {
				if (!this.recordedVideoUrl) return;

				uni.saveVideoToPhotosAlbum({
					filePath: this.recordedVideoUrl,
					success: () => {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
						// 保存成功后清除本地引用
						this.recordedVideoUrl = null;
					},
					fail: (err) => {
						console.error('保存视频失败:', err);
						uni.showToast({
							title: '保存失败，请重试',
							icon: 'none'
						});
					}
				});
			}
		}
	};
</script>

<style scoped>
	/* 样式与之前版本保持一致 */
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.section {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 20rpx;
		display: block;
	}

	.operation-btn {
		padding: 15rpx 30rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		background-color: #4285f4;
		color: #ffffff;
		border: none;
	}

	.operation-btn:disabled {
		background-color: #cccccc;
		color: #666666;
	}

	.start-btn {
		background-color: #00c853;
	}

	.stop-btn {
		background-color: #d32f2f;
	}

	.save-btn {
		background-color: #ff9800;
		margin-top: 10rpx;
		margin-left: 30rpx;
	}

	.control-group {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 20rpx;
	}

	.hint {
		font-size: 24rpx;
		color: #666666;
		margin-bottom: 20rpx;
		display: block;
	}

	.recording-status {
		display: flex;
		align-items: center;
		color: #d32f2f;
		margin: 10rpx 0;
		font-size: 26rpx;
		font-weight: 500;
	}

	.recording-dot {
		width: 16rpx;
		height: 16rpx;
		background-color: #ff3b30;
		border-radius: 50%;
		margin-right: 10rpx;
		animation: pulse 1.5s infinite;
	}

	.warning-message {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background-color: #fff8e1;
		border-radius: 8rpx;
		margin-top: 20rpx;
		color: #ff6d00;
		font-size: 26rpx;
	}

	.success-message,
	.success-group {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background-color: #e8f5e9;
		border-radius: 8rpx;
		margin-top: 20rpx;
		color: #2e7d32;
		font-size: 26rpx;
	}

	.success-group {
		flex-wrap: wrap;
	}

	.warning-icon,
	.success-icon {
		margin-right: 10rpx;
		font-size: 30rpx;
	}

	@keyframes pulse {
		0% {
			opacity: 1;
		}

		50% {
			opacity: 0.4;
		}

		100% {
			opacity: 1;
		}
	}
</style>